<?php
/**
 * Created by PhpStorm.
 * User: River
 * Email: river0428@gmail.com
 * Date: 2018/10/30
 * Time: 上午10:43
 */
namespace Modules\Api\Controllers;

use App\Models\Configure;
use App\Models\Coupon;
use App\Models\OilCard;
use App\Models\Pay;
use App\Models\Recharge;
use App\Models\RechargeOrder;
use App\Models\RechargeTask;
use App\Models\User;
use App\Models\UserCoupon;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Modules\Token\Facades\Token;

class RechargeController extends Controller
{
    public function index()
    {
        $uid  = Token::data('id');
        $user = User::find($uid);

        $data = [
            'items'     => [],
            'oil_cards' => [],
        ];

        $cards = OilCard::query()->where('user_id',$uid)->where('status',1)->get();

        foreach ($cards as $card) {
            $item                     = $card->toArray();
            $item['month_recharged']  = $card->getCurrentMonthRechargedAmount(); // 本月已返还
            $item['month_recharging'] = $card->getCurrentMonthAmount(); // 本月应返还
            $data['oil_cards'][]      = $item;
        }

        $data['items'] = Recharge::orderBy('discount', 'desc')->get()->toArray();

        $data['discount'] = (string)Configure::rechargeDiscount();

        $data['amounts'] = [
            '100',
            '200',
            '500',
            '1000',
            '2000',
            '5000',
        ];

        return success($data);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $user = User::find(Token::data('id'));

            if (!$user) {
                return fail(403, '用户不存在');
            }

            $oilCardId   = $request->input('oil_card_id');//绑定的油卡id
            $amount      = $request->input('amount');//充值金额
            $rechargeId  = $request->input('recharge_id');//套餐id
            $useCouponId = $request->input('use_coupon_id');//优惠券id
            $openId      = $request->input('open_id');//微信支付需要的openId

            $paymentMethod = $request->input('payment_method', 'weixin');

            if (!$user['open_id'] && !$openId && $paymentMethod == 'weixin') {
                return fail(400, 'open_id不能为空');
            }
            if ($openId) {
                User::where('id', $user['id'])->update(['open_id' => $openId]);
            }

//            $users = DB::table('oil_card')->where('card_no',$oilCardId)->get();
//            if ($users){
//                return fail(400, '卡号不存在');
//            }

            if (!$oilCardId OR !$amount) {
                return fail(400, '参数错误');
            }

            $card = OilCard::find($oilCardId);
            if (!$card) {
                return fail(400, '参数错误');
            }

            $amount = formatPrice($amount);

            if ($useCouponId) {
                $useCoupon = UserCoupon::where('status', UserCoupon::STATUS_NEW)
                    ->where('user_coupon.id', $useCouponId)
                    ->where('user_id', $user->id)
                    ->first();
                if (!$useCoupon OR $useCoupon->isExpired()) {
                    return fail(400, '优惠券无效，请重新选择');
                }

                $months = 1;

                if($rechargeId){
                    $recharge = Recharge::find($rechargeId);
                    if (!$recharge) {
                        return fail(400, '套餐不存在');
                    }
                    $months = $recharge->months;
                }

                //验证优惠券的合法性
                $couponInfo = Coupon::query()->find($useCoupon->coupon_id);
                if(!$couponInfo) return fail(1016,'无效的优惠券');
                //验证消费金额
                $totalAmount = $amount * $months;
                if($couponInfo->min_amount > 0 && $totalAmount < $couponInfo->min_amount){
                    Log::error('coupon error:' . $useCoupon->user_id . '-' . $useCoupon->id . ':' . $totalAmount . '<' . $couponInfo->min_amount);
                    return fail(1016,'优惠券无效,充值金额不满足使用条件');
                }

                //验证月数
                if($months < $couponInfo->months){
                    Log::error('coupon months error:' . $useCoupon->user_id . '-' . $useCoupon->id . ':' . $months . '<' . $couponInfo->months);
                    return fail(1016,'优惠券无效,充值套餐月数必须不能小于' . $couponInfo->months);
                }

                //冻结优惠券
                $useCoupon->status = 4;
                $useCoupon->used_at = Carbon::now();
                $useCoupon->save();


            } else {
                $useCoupon = null;
            }
            //

            // 套餐充值
            if ($rechargeId) {

                // 是否是首充
                $isFirst = true;
                if (RechargeOrder::where('user_id', $user->id)->where('status', '>', 0)->count()) {
                    $isFirst = false;
                }

                $recharge = Recharge::find($rechargeId);
                if (!$recharge) {
                    return fail(400, '套餐不存在');
                }

                $payAmount = formatPrice(($amount * $recharge->months) * $recharge->discount);
                // 使用优惠券
                if ($useCoupon) {
                    // 代金券
                    if ($useCoupon->type == UserCoupon::TYPE_MONEY) {
                        $payAmount = $payAmount - $useCoupon->amount;
                        $payAmount = $payAmount < 0 ? 0 : $payAmount;
                    }
                    // 特权券，可以使用首充限制的套餐
                    if ($useCoupon->type == UserCoupon::TYPE_RECHARGE && $useCoupon->recharge_id == $recharge->id) {
                        $isFirst = true;
                    }
                    // // 标记已使用
                    // $useCoupon->status  = UserCoupon::STATUS_USED;
                    // $useCoupon->used_at = Carbon::now()->toDateTimeString();
                    // $useCoupon->save();
                }

                // 是不是仅限首充
                if ($recharge->only_first) {
                    if (!$isFirst) {
                        return fail(400, '只有首次充值才能选择此套餐');
                    }
                }

                // if (!$useCouponId) {
                //     $useCouponId = 0;
                // }

                $order                  = new RechargeOrder();
                $order->type            = 1;//套餐为1直充为2
                $order->oil_card_id     = $card->id;
                $order->user_id         = $user->id;
                $order->recharge_id     = $rechargeId;
                $order->recharge_amount = $amount;
                $order->pay_amount      = $payAmount;
                $order->months          = $recharge->months;
                $order->coupon_id       = $useCouponId;
                $order->discount        = $recharge->discount;
                $order->status          = 0;
                $order->card_no         = $card->card_no;
                $order->card_mobile     = $card->mobile;
                $order->card_type       = $card->type;

            } else {
                // 直接充值

                if ($amount < 100 OR ($amount % 100) > 0) {
                    //return fail(400, '充值金额有误');
                }

                $payAmount = formatPrice($amount * Configure::rechargeDiscount());

                // 使用优惠券
                if ($useCoupon) {
                    if ($useCoupon->only_recharge) {
                        return fail(400, '优惠券仅限充值套餐时使用');
                    }
                    if ($useCoupon->type == UserCoupon::TYPE_MONEY) {
                        //$payAmount = $payAmount - $useCoupon->amount;
                        //$payAmount = $payAmount < 0 ? 0 : $payAmount;
                    }
                }

                $order                  = new RechargeOrder();
                $order->type            = 2;//套餐为1直充为2
                $order->oil_card_id     = $card->id;
                $order->user_id         = $user->id;
                $order->recharge_amount = $amount;
                $order->pay_amount      = $payAmount;
                $order->coupon_id       = $useCouponId;
                $order->discount        = Configure::rechargeDiscount();
                $order->status          = 0;
                $order->card_no         = $card->card_no;
                $order->card_mobile     = $card->mobile;
                $order->card_type       = $card->type;

            }

            if (!$rechargeId) {
                    $rechargeId = 0;
                    Log::error('22222');
                }
            if ($useCouponId !== null && $useCoupon->coupon_id == 9 && $payAmount < 3000) {
                 return fail(400, '此优惠券仅限充值套餐满3000时使用'); 
            }

            // 创建支付单
            $pay                 = new Pay();
            $pay->payment_method = $paymentMethod;
            $pay->user_id        = $user->id;
            $pay->pay_sn         = Pay::makeYouKaPaySN();
            $pay->amount         = $order->pay_amount;
            $pay->save();

            $order->pay_id = $pay->id;//支付流水id
            $order->save();

            $response = [
                'order_id'       => $order->id,
                'payment_method' => $paymentMethod,
                'pay_info'       => null,
            ];

            $response['pay_info']   = '';
            $response['weixin_app'] = null;
            if ($paymentMethod == 'alipay') {
                $response['pay_info'] = Pay::alipay($pay);
            }
            if ($paymentMethod == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp($pay);
            }
            if ($paymentMethod == 'weixin') {
                $response['weixin'] = Pay::weixin($pay, $openId);
            }

            DB::commit();

            return success($response);
        } catch (\Exception $e) {
            Log::error($e);
            DB::rollBack();
            return fail(500, '系统错误');
        }
        // // 标记已使用
        // $useCoupon->status  = UserCoupon::STATUS_USED;
        // $useCoupon->used_at = Carbon::now()->toDateTimeString();
        // $useCoupon->save();
    }

    public function paymentMethods()
    {
        $data['items'] = [
            [
                'name' => '微信支付',
                'code' => 'weixin_app',
                'icon' => env('APP_URL') . '/files/pay-weixin.jpg',
            ],
            [
                'name' => '支付宝',
                'code' => 'alipay',
                'icon' => env('APP_URL') . '/files/pay-alipay.jpg',
            ]
        ];

        return success($data);
    }

    public function pay($id, Request $request)
    {
        //未支付订单再次支付
        try {
            $order         = RechargeOrder::find($id);
            $paymentMethod = $request->input('payment_method');
            $user = User::find(Token::data('id'));
            Log::error($user->id);
            //更改支付方式
            $pay                 = $order->pay;
            $pay->payment_method = $paymentMethod;
            $pay->save();

            $response = [
                'order_id'       => $order->id,
                'payment_method' => $paymentMethod,
                'pay_info'       => null,
            ];
            //支付序号
            if ($pay->pay_sn) {
                //$pay->pay_sn = Pay::makeYouKaPaySN();
            }
            $response['pay_info']   = '';
            $response['weixin_app'] = null;
            if ($paymentMethod == 'alipay') {
                $response['pay_info'] = Pay::alipay_num($pay);
            }
            if ($paymentMethod == 'weixin_app') {
                $response['weixin_app'] = Pay::weixinApp_num($pay);
            }
            if ($paymentMethod == 'weixin') {
                $response['weixin'] = Pay::weixin_num($pay, $user['open_id']);
            }
            return success($response);
        } catch (\Exception $e) {
            Log::error($e);
            return fail(500, '系统错误');
        }
    }

    public function order(Request $request)
    {  
        $type   = $request->input('type');
        $status = $request->input('status', false) ?: false;
        $orderId = $request->input('orderId', false) ?: false;

        $user   = User::find(Token::data('id'));
    
        $limit  = $request->input('limit', 20);
        $offset = $request->input('offset', 0);

        if ($orderId) {
            DB::table('recharge_order')->where('id', $orderId)->update(['status' => -1]);
        }

        $data = ['items'=>[],'total'=>0];

        $query = RechargeOrder::query();
        if ($status == 0) {
            $query = $query->where('status', RechargeOrder::STATUS_INIT)    //待支付 0
            ->where('user_id', $user->id);
            $data['total'] = $query->count();
            for ($i=0; $i < $query->count(); $i++) {
               $data['items'] = $query->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $a = intval($value['recharge_amount']);
                        $data['items'][$key]['nickname'] = $a.'元油卡直充';
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月油卡套餐';
                    } 
                }
            }   
        }
        if ($status == 1) {
            $query_two = RechargeOrder::query();
            $query_two = $query_two->where('status', RechargeOrder::STATUS_PAID)      //进行中  1
            ->where('user_id', $user->id);
            $data['total'] = $query_two->count();
            for ($i=0; $i < $query_two->count(); $i++) {
               $data['items'] = $query_two->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $a = intval($value['recharge_amount']);
                        $data['items'][$key]['nickname'] = $a.'元油卡直充';
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月油卡套餐';
                    } 
                }
            }   
        }
        if ($status == 3) {
            $query_three = RechargeOrder::query();
            $query_three = $query_three->where('status', RechargeOrder::STATUS_DONE)   //已完成   3
            ->where('user_id', $user->id);
            $data['total'] = $query_three->count();
            for ($i=0; $i < $query_three->count(); $i++) {
               $data['items'] = $query_three->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $a = intval($value['recharge_amount']);
                        $data['items'][$key]['nickname'] = $a.'元油卡直充';
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月油卡套餐';
                    } 
                }
            }   
        }
        if ($status == 5) {
            $query_four = RechargeOrder::query();
            $query_four = $query_four->where('user_id', $user->id);   //全部    5
            $data['total'] = $query_four->count();
           for ($i=0; $i < $query_four->count(); $i++) {
               $data['items'] = $query_four->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $a = intval($value['recharge_amount']);
                        $data['items'][$key]['nickname'] = $a.'元油卡直充';
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月油卡套餐';
                    } 
                }
            }   
        }
        if ($status == -1) {
            $query_five = RechargeOrder::query();
            $query_five = $query_five->where('status', -1)       //已退订   -1
            ->where('user_id', $user->id);
            $data['total'] = $query_five->count();
            for ($i=0; $i < $query_five->count(); $i++) {
               $data['items'] = $query_five->take($limit)->offset($offset)
                ->with('oilCard')
                ->orderBy('id', 'desc')->get();
                foreach ($data['items'] as $key => $value) {
                    if ($value['type'] == 2) {
                        $a = intval($value['recharge_amount']);
                        $data['items'][$key]['nickname'] = $a.'元油卡直充';
                    }else{
                        $data['items'][$key]['nickname'] = $value['months'].'个月油卡套餐';
                    } 
                }
            }   
        }
        
        if ($type) {
            $query = $query->where('type', $type);
        }
        $query->when($status, function ($q) use ($status) {
            $q->where('status', $status);
        });
        return success($data);
    }

    public function order_detail(Request $request)
    {
        $type   = $request->input('type');
        $orderid = $request->input('order_id');
        $query_two = RechargeOrder::where('id',$orderid)->get();
        $data = [];
        //取订单任务表的详细数据
        if (!empty($orderid) && $query_two[0]['status'] == 1 or $query_two[0]['status'] == 3) {
            $query_one = RechargeTask::where('recharge_order_id',$orderid)->orderBy('pay_at', 'asc')->get();//根据订单id 查询充值详情列表
            $query_two = RechargeOrder::where('id',$orderid)->get();
            for ($i=0; $i < $query_one->count(); $i++) { 
                $data['items'] = $query_one;
                $a = 1;
                foreach ($query_one as $key => $value) {
                    $data['status'] = $query_two[0]['status'];
                    $data['card_type'] = $value->card_type;
                    $data['card_no'] = $value->card_no;
                    $data['card_mobile'] = $value->card_mobile;
                    $data['recharge_order_detail_id'] = $value->recharge_order_detail_id;
                    $data['recharge_amount'] = $query_two[0]['recharge_amount'];
                    $data['pay_amount'] = $query_two[0]['pay_amount'];
                    $data['order_id'] = $query_two[0]['id'];

                    $c = $query_two[0]['created_at'];
                    $year = date('Y-m-d',strtotime($c));
                    $data['created_at'] = $year;

                    $data['items'][$key]['benqi'] = intval($query_two[0]['recharge_amount']);
                    $data['items'][$key]['months'] = $query_two[0]['months'];
                    $data['items'][$key]['qishu'] = $a++;
                    $year = date('Y-m-d',strtotime($value->pay_at));
                    $data['items'][$key]['pay_at'] = $year;

                    //$years = date('Y-m-d',strtotime($value->created_at));
                    $data['items'][$key]['created_two_at'] = $year;

                    if ($query_two[0]['coupon_id']) {
                        $sql = UserCoupon::where('id',$query_two[0]['coupon_id'])->get();
                        if ($sql) {
                            $data['coupon_id'] = $sql[0]['title'];
                        }
                    }else{
                        $data['coupon_id'] = '未使用优惠券';
                    }
                }
            }
        }

        if (!empty($orderid) && $query_two[0]['status'] == 0 or $query_two[0]['status'] == -1) {
                    $user = DB::table('oil_card')->where('id', $query_two[0]['oil_card_id'])->first();
                    Log::error($query_two[0]['oil_card_id']);
                    $arr = array();
                    $data['items'] = $arr;
                    $data['card_type'] = $user->type;
                    $data['card_no'] = $user->card_no;
                    $data['card_mobile'] = $user->mobile;
                    $data['status'] = $query_two[0]['status'];
                    $data['recharge_amount'] = $query_two[0]['recharge_amount'];
                    $data['pay_amount'] = $query_two[0]['pay_amount'];
                    $data['order_id'] = $query_two[0]['id'];

                    $c = $query_two[0]['created_at'];
                    $year = date('Y-m-d',strtotime($c));
                    $data['created_at'] = $year;

                    $data['recharge_type'] = $query_two[0]['type'];
                    if ($query_two[0]['coupon_id']) {
                        $sql = UserCoupon::where('id',$query_two[0]['coupon_id'])->get();;
                        if ($sql) {
                            $data['coupon_id'] = $sql[0]['title'];
                        }
                    }else{
                        $data['coupon_id'] = '未使用优惠券';
                    }
        }
        return success($data);
    }

    public function testPay($id)
    {
        try {
            $order = RechargeOrder::find($id);
            if (!$order) {
                return fail(404, 'order not exists');
            }
            //Pay::setPaid($order->pay);
            return success();
        } catch (\Exception $e) {
            Log::error($e);
            return fail(500, '系统错误');
        }
    }
}